<?php
/**
 * Created by PhpStorm.
 * User: cc
 * Date: 2022/1/20
 * Time: 11:23 上午
 */

namespace App\Models\CacheModel\live;

use App\Models\Api\BaseCache;

/**
 * Class LiveAnswerReward
 * @package App\Models\CacheModel\live
 */
class LiveAnswerReward extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.live_answer_reward';


    /**
     * 添加打赏
     * @param $data
     * @return int|string
     */
    public function saveData($data)
    {
        try
        {
            $id = $this->insertGetId($data);
        }
        catch (\Exception $e)
        {
            $id = 0;
        }
        return $id;
    }

    /**
     * 获取解答打赏收益
     * @param $liveRecordIds
     * @return array
     */
    public function getAnswerReward($liveRecordIds)
    {
        // return $this->whereIn('live_record_id', $liveRecordIds)->sum('coin');

        $data = $this->whereIn('live_record_id', $liveRecordIds)->group('type,coin')->field('type,coin,reason,count(id) as num')->order('type asc')->select();

        $resData = [
            'total_coin' => 0,
            'reward_info_desc' => ''
        ];

        foreach ($data as $datum)
        {
            switch ($datum['type'])
            {
                case 1:
                    $resData['total_coin'] += ($datum['coin'] * $datum['num']);
                    $resData['reward_info_desc'] .= sprintf("看盘打赏%d准币x%d、", $datum['coin'], $datum['num']);
                    break;
                case 2:
                    $resData['total_coin'] += ($datum['coin'] * $datum['num']);
                    $resData['reward_info_desc'] .= sprintf("骰子打赏%d准币x%d、", $datum['coin'], $datum['num']);
                    break;
                case 3:
                    $resData['total_coin'] += ($datum['coin'] * $datum['num']);
                    $resData['reward_info_desc'] .= sprintf("塔罗打赏%d准币x%d、", $datum['coin'], $datum['num']);
                    break;
                default:
            }
        }

        $resData['reward_info_desc'] = rtrim($resData['reward_info_desc'], '、');
        return $resData;
    }

    /**
     * 获取用户解答 打赏准币数
     * @param int $type 1=>看盘，2=>骰子，3=>塔罗
     * @param int $answerId 解答问题ID
     * @return float|int|string|null
     */
    public function getUserAnswerReward(int $type, int $answerId)
    {
        return $this->where(['type' => $type, 'answer_id' => $answerId])->sum('coin');
    }
}
